/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.orderControllers', ['ui.router'])
    .config(function($stateProvider, $urlRouterProvider){
        $stateProvider
            .state('tab.orderDetail' ,{
                url:'/myOrders/orderdetail',
                templateUrl:'view/carrier/order/order-detail.html',
                controller:'OrderDetailCtrl'
            })
            .state('tab.orderComment' ,{
                url:'/myOrders/ordercomment',
                templateUrl:'view/carrier/order/order-comment.html',
                controller:'OrderCommentCtrl'
            })
            .state('tab.orderCars' ,{
                url:'/myOrders/ordercars'
                ,templateUrl:'view/carrier/order/order-cars.html'
                ,controller:'OrderCarsCtrl'
            })
            .state('tab.bidDetail' ,{
                url:'/bid/biddetail'
                ,templateUrl:'view/carrier/bid/biddetail.html'
                ,controller:'BidDetailCtrl'
            })
    })
    .filter('dateFormat' ,function(){
        return function(input){
            if(typeof input == 'string'){
                return input.substring(0 ,10);
            }
        }
    })
    .filter('orderState' ,function(){
        return function(input){
            if(input.status == 1 ){return '已报价'}
            if(input.status == 2 && input.accept == 1){return '已接受'}
            if(input.status == 2 && input.accept ==0){return '已结束'}
            if(input.status == 3){return '已评价'}
            if(input.status == 5 || input.status == 4){return '已取消'}

        }
    })
    .controller('MyOrderCtrl',function($scope,$rootScope,$state,$http ,OrderService){
        /*$scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);*/
        $('#order-wrapper').css('min-height',$(window).height()-136+'px');

        var user = JSON.parse(localStorage.user)

        var s = OrderService;
        $scope.switch = s.switch();
        var order = $scope.orders = s.orders();//重新打开我的订单页面时，从OrderService初始化数据
        if(order.userid!=user.id || $rootScope.refreshOrder){
            order[0].total = order[1].total = undefined;
            $rootScope.refreshOrder = false;
        }
        /*if(order[$scope.switch].total === undefined){
            loadOrder();
        }*/

        pull($scope,"wrapper",function(pull){
            if('pullDown'==pull) {//下拉刷新
                s.load({scope:$scope});
            }else{//上拉加载更多
                s.more({scope:$scope});
            }
        });

        //切换订单tab选项
        $scope.switchOrders = function(idx){
            $scope.switch = idx;
            $('.noorder').hide();
            if(idx==0){
                $('.order1').hide();
                $('.order0').show();
            }else{
                $('.order0').hide();
                $('.order1').show();
            }
            s.switch(idx ,$scope);
        }
        $scope.switchOrders($scope.switch);

        //跳转到订单详情页
        $scope.goDetail = function(idx){
            s.index[$scope.switch] = idx;
            $state.go('tab.orderDetail');
        }


        var config = {
            timeout:8000
        }
        function loadOrder(){
            OrderService.busy = true;

            var params = OrderService.param();
            var page = params.page;//如果加载失败，恢复之前的页数
            params.page = 1;
            $http.post('/users/myorders' ,params ,config)
                .success(function(data,status) {
                    if(data.err){
                        params.page = page;
                    }else{
                        truncateOrder(data.rows);
                        OrderService.putOrder(data );
                        $scope.$apply();

                        refreshScroll();
                    }
                    OrderService.busy = false;

                })
                .error(function (data,status) {
                    params.page = page;
                    OrderService.busy = false;
                });

        }

        function moreOrder(){
            var status = OrderService.status();
            /*if(status.total == status.length){//所有数据都已被加载
             return;
             }*/
            if(!$scope.orders[$scope.switch].length){//如果没有数据，加载第一页
                loadOrder();
                return;
            }
            var params = OrderService.param();
            params.page += 1;
            OrderService.busy = true;
            $http.post('/users/myorders' ,params ,config)
                .success(function(data) {
                    if(data.err){
                        params.page -= 1;
                    }else{
                        truncateOrder(data.rows);
                        OrderService.appendOrder(data );
                        $scope.$apply();
                    }
                    OrderService.busy = false;

                    refreshScroll();

                })
                .error(function (data,status) {alert(status);
                    params.page -= 1;
                    OrderService.busy = false;

                });
        }

        function truncateOrder(rows){
            var rs = rows;
            for(var x in rs){
                var i = rs[x];
                var carnums = i.carnum.split(',');
                i.carnums = carnums;
                var nums = i.num.split(',');
                var totalnum = 0;
                for(var xx in nums){
                    nums[xx] = Number(nums[xx]);
                    totalnum += nums[xx];
                }
                i.nums = nums;
                i.total = totalnum;
                //i.note = '本次共运送'+carnums.length+'种型号共'+totalnum+'辆车';
            }

        }

        function refreshScroll(){
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },600);
        }
    })
    .controller('OrderDetailCtrl' ,function($scope ,$state ,$http ,OrderService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var s = OrderService;
        var order = $scope.order = s.order();
        if(!order.hasDetail){
            $http.post('/users/carrierorderdetail' ,{id:order.id})
                .success(function(data){
                    if(data.err){

                    }else{
                        order.hasDetail = true;
                        order.carrier = data.carrier;
                        order.user = data.user;
                        order.comment = data.comment;
                        if(order.type == 1){
                            //s.order(data)
                            order.cars = data.cars;
                        }
                        setTimeout(function(){
                            $scope.myScroll.refresh();
                        },600);
                    }
                })
                .error(function(data){

                })
        }

        $scope.go = function(state){
            $state.go(state);
        }
        $scope.goComment = function(){
            if(order.status != 3)return;
            $state.go('tab.orderComment');
        }

    })
    .controller('OrderCarsCtrl' ,function($scope ,$state ,OrderService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var order = $scope.order = OrderService.order();
        var cars = $scope.cars = order.cars;
        $scope.popIdx = undefined;
        if(order.type==1){
            $scope.orderCount = order.total + '辆车';
        }else{
            $scope.orderCount = '';
            for(var x in cars){
                $scope.orderCount += cars[x].num+'个'+cars[x].type
            }
        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);
    })
    .controller('OrderCommentCtrl' ,function($scope ,$state ,$http ,OrderService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var order = OrderService.order();
        var carrier = $scope.carrier = order.carrier;

        //$scope.flag = order.status == 3;
        $scope.flag = true;
        if($scope.flag){
            $scope.comment = order.comment;
            document.getElementById('commentText').disabled = true;
        }
        $scope.authImg = (order.carrier.carrierauthstate == 1 ? 'icon-icon-18' : 'icon-icon-19');
        $scope.authText = (order.carrier.carrierauthstate == 1 ? '已认证' : '未认证');
        $scope.postText = $scope.flag?'已 评 价':'评 价';


        //评价打分
        $scope.graderArray = [1,2,3,4,5];
        setTimeout(function(){
            $scope.myScroll.refresh();
        },300);
        //
        $scope.go = function(state){
            $state.go(state);
        }
    })
    .controller('MyBidCtrl' ,function($scope ,$rootScope ,$state ,BidService){
        /*//初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);*/
        $('#bid-content').css('min-height',$(window).height()-94+'px');
        pull($scope,"wrapper",function(pull){
            if(s.busy)return;
            if('pullDown'==pull) {//下拉刷新
                s.load(param);
            }else{//上拉加载更多
                s.more(param);
            }
        });

        var user = JSON.parse(localStorage.user)
        var s = BidService;
        var bids = $scope.bids = s.bids;
        var param = {
            scroll:$scope.myScroll
        }
        if(bids.total === undefined || $rootScope.refreshBid || user.id!=bids.userid){
            s.load(param);
            $rootScope.refreshBid = false;
        }
        setTimeout(function(){
            $scope.myScroll.refresh();
        },300)
        $scope.goDetail = function(idx){
            s.index = idx;
            $state.go('tab.bidDetail')
        }
        //showToast('test')
    })
    .controller('BidDetailCtrl' ,function($scope ,$http ,BidService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        function truncateBid(){
            if(bid.type == 2){
                var nums = bid.carnum.split(',')
                $scope.nums = [];
                if(nums[0]){
                    $scope.nums.push({type:'小板',num:nums[0]})
                }
                if(nums[1]){
                    $scope.nums.push({type:'大板',num:nums[1]})
                }
            }
        }
        var s = BidService;
        var bid = $scope.bid = s.bids.rows[s.index];
        if(bid.type == 1 && !bid.cars){
            $http.post('/users/orderdetail' ,{id:bid.inforid})
                .success(function(data){
                    if(data.err){

                    }else{
                        $scope.cars = bid.cars = data.cars;
                        setTimeout(function(){
                            $scope.myScroll.refresh();
                        } ,300)
                    }
                })
        }
        truncateBid();
        $scope.popIdx = undefined;
        /*$
        $scope.closePop = function(){
            $('#popImg').hide();
        }*/


        setTimeout(function(){
            $scope.myScroll.refresh();
        },300);
    });


function showToast(msg){
    var wHeight = window.innerHeight;
    var wWidth = window.innerWidth;
    var top = wHeight*0.7;
    var toast = $('<div></div>');
    var tip = $('<span></span>')
    toast.append(tip);
    tip.text(msg);
    toast.css({
        'position':'fixed'
        ,'z-index':'5000'
        //,top:top+'px'
        ,bottom:'80px'
        ,color:'#666'
        ,'text-align':'center'
        ,width:wWidth+'px'
    })
    tip.css({
        padding:'10px'
        ,'background-color':'#bbb'
        ,'border-radius':'5px'
    })
    $(document.body).append(toast);
    setTimeout(function(){
        toast.remove();
    },2500)
}